package com.example.contextcube;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;

import com.example.contextcube.util.SharedPrefsUtil;
import com.example.contextcube.util.ToastManager;
import com.example.contextcube.util.UserManager;
import com.google.android.material.card.MaterialCardView;
import com.google.android.material.textfield.TextInputLayout;

public class LoginActivity extends AppCompatActivity {
    private static final String TAG = "LoginActivity";
    
    // 界面状态：登录或注册
    private enum State {
        LOGIN,
        REGISTER
    }
    
    // 当前界面状态
    private State currentState = State.LOGIN;
    
    // 界面元素
    private ConstraintLayout rootLayout;
    private MaterialCardView cardView;
    private TextInputLayout usernameLayout;
    private TextInputLayout passwordLayout;
    private TextInputLayout confirmPasswordLayout;
    private EditText usernameInput;
    private EditText passwordInput;
    private EditText confirmPasswordInput;
    private Button actionButton;
    private TextView switchModeText;
    private ImageView logoImage;
    
    // 用户管理器
    private UserManager userManager;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        
        // 设置状态栏透明
        getWindow().setStatusBarColor(Color.TRANSPARENT);
        getWindow().setFlags(
                WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
                WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
        );
        
        // 初始化用户管理器
        userManager = new UserManager(this);
        
        // 初始化视图
        initViews();
        
        // 设置监听器
        setupListeners();
        
        // 播放进入动画
        playEntranceAnimation();
    }
    
    /**
     * 初始化视图
     */
    private void initViews() {
        rootLayout = findViewById(R.id.root_layout);
        cardView = findViewById(R.id.card_view);
        usernameLayout = findViewById(R.id.username_layout);
        passwordLayout = findViewById(R.id.password_layout);
        confirmPasswordLayout = findViewById(R.id.confirm_password_layout);
        usernameInput = findViewById(R.id.username_input);
        passwordInput = findViewById(R.id.password_input);
        confirmPasswordInput = findViewById(R.id.confirm_password_input);
        actionButton = findViewById(R.id.action_button);
        switchModeText = findViewById(R.id.switch_mode_text);
        logoImage = findViewById(R.id.logo_image);
        
        // 设置初始状态为登录
        updateUIForState(State.LOGIN);
    }
    
    /**
     * 设置监听器
     */
    private void setupListeners() {
        // 输入框文本变化监听
        TextWatcher textWatcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
            
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}
            
            @Override
            public void afterTextChanged(Editable s) {
                validateInputs();
            }
        };
        
        usernameInput.addTextChangedListener(textWatcher);
        passwordInput.addTextChangedListener(textWatcher);
        confirmPasswordInput.addTextChangedListener(textWatcher);
        
        // 登录/注册按钮点击事件
        actionButton.setOnClickListener(v -> {
            if (currentState == State.LOGIN) {
                login();
            } else {
                register();
            }
        });
        
        // 切换模式文本点击事件
        switchModeText.setOnClickListener(v -> {
            if (currentState == State.LOGIN) {
                updateUIForState(State.REGISTER);
            } else {
                updateUIForState(State.LOGIN);
            }
        });
    }
    
    /**
     * 播放进入动画
     */
    private void playEntranceAnimation() {
        // Logo动画
        logoImage.setAlpha(0f);
        logoImage.animate()
                .alpha(1f)
                .setDuration(800)
                .start();
        
        // 卡片动画
        cardView.setAlpha(0f);
        cardView.setTranslationY(200f);
        cardView.animate()
                .alpha(1f)
                .translationY(0f)
                .setDuration(1000)
                .setStartDelay(300)
                .start();
    }
    
    /**
     * 根据当前状态更新UI
     */
    private void updateUIForState(State state) {
        currentState = state;
        
        if (state == State.LOGIN) {
            // 登录模式
            confirmPasswordLayout.setVisibility(View.GONE);
            actionButton.setText(R.string.login);
            switchModeText.setText(R.string.no_account_register);
        } else {
            // 注册模式
            confirmPasswordLayout.setVisibility(View.VISIBLE);
            actionButton.setText(R.string.register);
            switchModeText.setText(R.string.have_account_login);
        }
        
        // 清空输入框错误提示
        usernameLayout.setError(null);
        passwordLayout.setError(null);
        confirmPasswordLayout.setError(null);
        
        // 验证输入
        validateInputs();
    }
    
    /**
     * 验证输入
     */
    private void validateInputs() {
        String username = usernameInput.getText().toString().trim();
        String password = passwordInput.getText().toString().trim();
        
        boolean isValid = true;
        
        // 用户名不能为空
        if (username.isEmpty()) {
            usernameLayout.setError(getString(R.string.error_username_empty));
            isValid = false;
        } else {
            usernameLayout.setError(null);
        }
        
        // 密码不能为空且长度至少为6位
        if (password.isEmpty()) {
            passwordLayout.setError(getString(R.string.error_password_empty));
            isValid = false;
        } else if (password.length() < 6) {
            passwordLayout.setError(getString(R.string.error_password_too_short));
            isValid = false;
        } else {
            passwordLayout.setError(null);
        }
        
        // 如果是注册模式，确认密码必须匹配
        if (currentState == State.REGISTER) {
            String confirmPassword = confirmPasswordInput.getText().toString().trim();
            if (confirmPassword.isEmpty()) {
                confirmPasswordLayout.setError(getString(R.string.error_confirm_password_empty));
                isValid = false;
            } else if (!confirmPassword.equals(password)) {
                confirmPasswordLayout.setError(getString(R.string.error_passwords_dont_match));
                isValid = false;
            } else {
                confirmPasswordLayout.setError(null);
            }
        }
        
        // 设置按钮可用状态
        actionButton.setEnabled(isValid);
    }
    
    /**
     * 登录操作
     */
    private void login() {
        String username = usernameInput.getText().toString().trim();
        String password = passwordInput.getText().toString().trim();
        
        if (userManager.authenticate(username, password)) {
            // 登录成功
            ToastManager.showShort(this, getString(R.string.login_successful));
            
            // 设置登录状态
            SharedPrefsUtil.saveLoggedInUser(this, username);
            
            // 跳转到主界面
            startMainActivity();
        } else {
            // 登录失败
            ToastManager.showShort(this, getString(R.string.login_failed));
            passwordLayout.setError(getString(R.string.error_invalid_credentials));
            
            // 抖动动画表示错误
            cardView.startAnimation(AnimationUtils.loadAnimation(this, R.anim.shake));
        }
    }
    
    /**
     * 注册操作
     */
    private void register() {
        String username = usernameInput.getText().toString().trim();
        String password = passwordInput.getText().toString().trim();
        
        if (userManager.isUserExists(username)) {
            // 用户已存在
            usernameLayout.setError(getString(R.string.error_username_exists));
            return;
        }
        
        // 注册用户
        if (userManager.createUser(username, password)) {
            // 注册成功
            ToastManager.showShort(this, getString(R.string.register_successful));
            
            // 自动切换到登录模式
            updateUIForState(State.LOGIN);
            
            // 填充用户名（密码已清空，需要用户再次输入）
            usernameInput.setText(username);
            passwordInput.setText("");
        } else {
            // 注册失败（由于本地存储问题或其他原因）
            ToastManager.showShort(this, getString(R.string.register_failed));
        }
    }
    
    /**
     * 启动主界面
     */
    private void startMainActivity() {
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        finish();
    }
} 